package com.kobeliu.service.impl;

import com.a3test.component.idworker.Snowflake;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.kobeliu.api.interceptor.JwtCurrentUserInterceptor;
import com.kobeliu.base.BaseInfoProperties;
import com.kobeliu.enums.OrderStatus;
import com.kobeliu.enums.PayMethod;
import com.kobeliu.enums.PaymentStatus;
import com.kobeliu.exceptions.GraceException;
import com.kobeliu.mapper.OrdersMapper;
import com.kobeliu.pojo.Orders;
import com.kobeliu.pojo.Users;
import com.kobeliu.pojo.bo.MerchantOrderBO;
import com.kobeliu.result.GraceJSONResult;
import com.kobeliu.result.ResponseStatusEnum;
import com.kobeliu.service.OrdersService;
import com.kobeliu.utils.LocalDateUtils;
import com.kobeliu.utils.PagedGridResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

@Service
@Slf4j
public class OrdersServiceImpl extends BaseInfoProperties implements OrdersService {

    @Autowired
    private OrdersMapper ordersMapper;

    @Autowired
    private Snowflake snowflake;

    @Autowired
    private RestTemplate restTemplate;

    @Override
    public String  createOrder() {

        //1.获取当前user信息
        Users users = this.getUsers();
        //获取companyId
        String hrInWhichCompanyId = users.getHrInWhichCompanyId();
        //获取userId
        String userId = users.getId();

        //生成一个雪花算法生成的Id
        String prefix = LocalDateUtils.format(LocalDate.now(),LocalDateUtils.DATETIME_PATTERN_3);
        String suffix = snowflake.nextId();

        Orders pending = new Orders();

        pending.setCompanyId(hrInWhichCompanyId);
        pending.setUserId(userId);
        pending.setId(prefix+suffix);

        pending.setCreatedTime(LocalDateTime.now());
        pending.setUpdatedTime(LocalDateTime.now());

        String itemName = "VIP企业用户";
        PayMethod payMethod = PayMethod.WEIXIN;
        Integer totalAmount = 1;

        pending.setItemName(itemName);
        pending.setPayMethod(payMethod.type);
        pending.setTotalAmount(totalAmount);
        pending.setRealPayAmount(totalAmount);
        pending.setStatus(OrderStatus.WAIT_PAY.type);
        pending.setPayMethod(totalAmount);

        ordersMapper.insert(pending);


        //创建本地订单，向支付中心发送订单，保存订单中的主要数据
        MerchantOrderBO bo = new MerchantOrderBO();
        bo.setMerchantOrderId(prefix+suffix);
        bo.setMerchantUserId(userId);
        bo.setMerchantCompanyId(hrInWhichCompanyId);

        bo.setAmount(pending.getTotalAmount());
        bo.setPayStatus(PaymentStatus.WAIT_PAY.type);
        bo.setPayMethod(PayMethod.WEIXIN.type);
        //设置回调地址，用于支付成功后修改订单状态
        bo.setReturnUrl(PAY_RETURN_URL);

        HttpHeaders headers = getHeadersForWxPay();
        //无法使用feign 因为不在同一个服务注册中心
        HttpEntity<MerchantOrderBO> entity = new HttpEntity<>(bo,headers);

        //发送请求到对应的url创建预订单
        ResponseEntity<GraceJSONResult> response = restTemplate.postForEntity(
                PAYMENT_URL_CREATE_MERCHANT_ORDER,
                entity,
                GraceJSONResult.class);

        // graceJSONResult
        GraceJSONResult payResult = response.getBody();

        if(payResult.getStatus() != 200){
            //失败
            GraceException.display(ResponseStatusEnum.PAYMENT_ORDER_CREATE_ERROR);
        }


        //返回订单号
        return prefix+suffix;
    }

    @Override
    public PagedGridResult getList(Integer page, Integer limit) {

        Users users = this.getUsers();

        PageHelper.startPage(page,limit);

        List<Orders> ordersList = ordersMapper.selectList(new QueryWrapper<Orders>()
                .like("company_id",users.getHrInWhichCompanyId())
                .like("user_id",users.getId()));

        return setterPagedGrid(ordersList,page);

    }

    private Users getUsers(){

        Users users = JwtCurrentUserInterceptor.currentUser.get();

        if(users == null
                || users.getHrInWhichCompanyId() == null
                || users.getId() == null){
            GraceException.display(ResponseStatusEnum.USER_STATUS_ERROR);
        }

        return users;
    }

    public HttpHeaders getHeadersForWxPay(){
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        //针对固定的用户测试用 要做校验 我用不了
        headers.add("imoocUserId","test");
        headers.add("passwd","test");

        return headers;
    }
}
